// src/graph_server.cpp
#include <iostream>
#include <memory>
#include <string>

#include <grpcpp/ext/proto_server_reflection_plugin.h>
#include <grpcpp/grpcpp.h>
#include <grpcpp/health_check_service_interface.h>

// 自己实现的服务类
#include "service/GraphDbService/GraphDbService.h" 

// 包含生成的服务定义
#include "generated/graph_service.grpc.pb.h"

#include "tools/DbClient/DbClient.h"

using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::Status;

class GraphServerRunner {
public:
    void Run(const std::string& server_address) {
        // 创建服务实现的实例
        // 这个实例将处理所有传入的 RPC 调用
        GraphDbService service;

        // 创建 ServerBuilder
        ServerBuilder builder;
        
        // 监听地址和端口
        builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
        
        // 注册服务实例
        builder.RegisterService(&service);
        
        // (可选) 设置最大消息大小等选项
        // builder.SetMaxMessageSize(1024 * 1024 * 10); // 10MB

        // 构建服务器
        std::unique_ptr<Server> server(builder.BuildAndStart());
        
        if (!server) {
            std::cerr << "Failed to build and start gRPC server." << std::endl;
            return;
        }
        
        std::cout << "GraphService gRPC Server listening on " << server_address << std::endl;

        // 等待服务器关闭 (这会阻塞主线程)
        // 服务器会一直运行，直到收到 SIGINT (Ctrl+C) 或 SIGTERM 信号
        server->Wait();
    }
};

int main(int argc, char** argv) {
    // 服务器监听地址和端口
    std::string server_address("0.0.0.0:8004"); 

    // 首次调用时传入连接参数
    DbClient::getInstance("bolt://neo4j:213007@localhost:7687", true);

    // 如果通过命令行参数指定了地址，则使用它
    if (argc > 1) {
        server_address = argv[1];
    }

    try {
        GraphServerRunner runner;
        std::cout << "Starting GraphService gRPC Server..." << std::endl;
        runner.Run(server_address);
    } catch (const std::exception& e) {
        std::cerr << "Server error: " << e.what() << std::endl;
        return 1;
    } catch (...) {
        std::cerr << "Unknown server error occurred." << std::endl;
        return 1;
    }

    std::cout << "GraphService gRPC Server stopped." << std::endl;
    return 0;
}